<template>
  <div class="article-manage">
    <el-card class="box-card">
      <!-- 搜索和操作工具栏 -->
      <div class="toolbar">
        <div class="search-box">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入标题关键词"
            clearable
            style="width: 200px;"
            @keyup.enter="handleQuery"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="queryParams.category" placeholder="文章类型" clearable>
            <el-option label="公告" value="NOTICE" />
            <el-option 
              label="心理知识" 
              value="KNOWLEDGE"
            />
          </el-select>
          <el-select v-model="queryParams.visibleRoles" placeholder="可见角色" clearable>
            <el-option label="所有人可见" value="all" />
            <el-option label="仅学生可见" value="student" />
            <el-option 
              label="仅咨询师可见" 
              value="counselor"
            />
          </el-select>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="已发布" value="1" />
            <el-option label="草稿" value="0" />
          </el-select>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </div>

      <!-- 文章列表 -->
      <el-table v-loading="loading" :data="articleList">
        <el-table-column label="标题" prop="title" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="handleTitleClick(row)">
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="类型" prop="category" width="100">
          <template #default="{ row }">
            <el-tag :type="row.category === 'NOTICE' ? 'warning' : 'success'">
              {{ row.category === 'NOTICE' ? '公告' : '心理知识' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="重要" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isImportant" type="danger">重要</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'info'">
              {{ row.status === '1' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="可见角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.visibleRoles === 'all' ? 'success' : row.visibleRoles === 'student' ? 'warning' : 'info'">
              {{ row.visibleRoles === 'all' ? '所有人可见' : row.visibleRoles === 'student' ? '仅学生可见' : '仅咨询师可见' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="280">
          <template #default="{ row, $index }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handlePreview(row)">预览</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button 
              link 
              type="primary" 
              :disabled="$index === 0" 
              @click="handleMoveUp(row, $index)"
            >
              上移
            </el-button>
            <el-button 
              link 
              type="primary" 
              :disabled="$index === articleList.length - 1" 
              @click="handleMoveDown(row, $index)"
            >
              下移
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      append-to-body
    >
      <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型" prop="category">
          <el-radio-group v-model="articleForm.category">
            <el-radio label="NOTICE">公告</el-radio>
            <el-radio label="KNOWLEDGE">心理知识</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否重要" v-if="articleForm.category === 'NOTICE'">
          <el-switch v-model="articleForm.isImportant" />
        </el-form-item>
        <el-form-item label="可见角色" prop="visibleRoles">
          <el-select v-model="articleForm.visibleRoles" placeholder="请选择可见角色">
            <el-option label="所有人可见" value="all" />
            <el-option label="仅学生可见" value="student" />
            <el-option 
              label="仅咨询师可见" 
              value="counselor"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Editor
            v-model="articleForm.content"
            :init="editorConfig"
          />
        </el-form-item>
        <el-form-item 
          label="封面图片" 
          prop="coverUrl" 
          v-if="articleForm.category === 'KNOWLEDGE'"
        >
          <el-upload
            class="cover-uploader"
            :action="'/api/upload/article'"
            :headers="{ Authorization: 'Bearer ' + getToken() }"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :on-error="(err: Error, file: File) => { console.error('上传失败:', err); ElMessage.error('上传失败，请重试') }"
            :before-upload="beforeCoverUpload"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <el-image
              v-if="articleForm.coverUrl"
              :src="articleForm.coverUrl"
              fit="cover"
              class="cover-image"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸: 800x400px，支持 jpg、png、gif 格式</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button @click="submitForm('draft', false)">保存草稿</el-button>
          <el-button type="primary" @click="submitForm('publish')">发布</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { getArticleList, addArticle, updateArticle, deleteArticle, updateArticleOrder } from '@/api/article'
import { useRouter } from 'vue-router'
import Editor from '@tinymce/tinymce-vue'
import { getToken } from '@/utils/auth'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  category: '',
  status: '',
  visibleRoles: '',
  orderBy: 'order_num asc'
})

// 文章列表数据
const loading = ref(false)
const total = ref(0)
const articleList = ref<any[]>([])

// 对话框数据
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单数据
const articleFormRef = ref<FormInstance>()
const articleForm = reactive({
  id: '',
  title: '',
  category: 'NOTICE',
  isImportant: false,
  content: '',
  status: '1',
  summary: '',
  visibleRoles: 'all',
  coverUrl: ''
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 添加 TinyMCE CDN 脚本
const script = document.createElement('script')
script.src = `https://cdn.tiny.cloud/1/j4upywlut9kn6p8oujhxuc6ab7yqwr7yj6kymwebm3awsini/tinymce/6/tinymce.min.js`
script.referrerPolicy = 'origin'
document.head.appendChild(script)

// 编辑器配置
const editorConfig = {
  height: 350,
  language: 'zh_CN',
  language_url: 'https://cdn.tiny.cloud/1/j4upywlut9kn6p8oujhxuc6ab7yqwr7yj6kymwebm3awsini/tinymce/6/langs/zh_CN.js',
  menubar: 'file edit view insert format tools table help',
  plugins: [
    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen', 'save',
    'insertdatetime', 'media', 'table', 'help', 'wordcount'
  ],
  toolbar: 'save | fullscreen | undo redo | blocks | ' +
    'bold italic forecolor | alignleft aligncenter ' +
    'alignright alignjustify | bullist numlist outdent indent | ' +
    'removeformat | image media | help',
  content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 14px; }',
  branding: false,
  promotion: false,
  resize: true,
  statusbar: false,
  paste_data_images: true,
  save_onsavecallback: () => {
    submitForm('draft', false)
  },
  images_upload_url: '/api/upload/article',
  images_upload_handler: async (blobInfo: any, success: (url: string) => void, failure: (err: string) => void) => {
    try {
      const formData = new FormData()
      formData.append('file', blobInfo.blob())
      
      const token = localStorage.getItem('token')
      if (!token) {
        failure('未登录')
        return
      }

      const response = await fetch('/api/upload/article', {
        method: 'POST',
        body: formData,
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        const error = await response.text()
        failure('上传失败: ' + error)
        return
      }

      const result = await response.json()
      if (result.code === 200) {
        success(result.data)
      } else {
        failure('图片上传失败：' + result.msg)
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      failure('图片上传失败，请重试')
    }
  },
  setup: function (editor: any) {
    editor.on('init', function () {
      console.log('编辑器初始化完成')
    })
  }
}

// 查询方法
const handleQuery = async () => {
  loading.value = true
  try {
    // 构造查询参数，确保visibleRoles正确传递
    const params = {
      ...queryParams,
      visibleRoles: queryParams.visibleRoles === '' ? undefined : queryParams.visibleRoles
    }
    const { data } = await getArticleList(params)
    articleList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('查询失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.category = ''
  queryParams.status = ''
  queryParams.visibleRoles = ''
  handleQuery()
}

// 新增按钮
const handleAdd = () => {
  dialog.title = '新增文章'
  dialog.visible = true
  articleForm.id = ''
  articleForm.title = ''
  articleForm.category = 'NOTICE'
  articleForm.isImportant = false
  articleForm.content = ''
  articleForm.status = '1'
  articleForm.summary = ''
  articleForm.coverUrl = ''
}

// 编辑按钮
const handleEdit = (row: any) => {
  dialog.title = '编辑文章'
  dialog.visible = true
  Object.assign(articleForm, row)
}

// 预览按钮
const handlePreview = (row: any) => {
  router.push(`/notice/detail/${row.id}`)
}

// 删除按钮
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认要删除该文章吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteArticle(Number(row.id))
      ElMessage.success('删除成功')
      handleQuery()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const submitForm = async (type = 'publish', closeDialog = true) => {
  if (!articleFormRef.value) return
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          id: articleForm.id,
          title: articleForm.title,
          content: articleForm.content,
          category: articleForm.category,
          isImportant: articleForm.isImportant,
          status: type === 'publish' ? '1' : '0',
          summary: articleForm.summary,
          visibleRoles: articleForm.visibleRoles,
          coverUrl: articleForm.coverUrl
        }

        if (articleForm.id) {
          await updateArticle(Number(articleForm.id), formData)
        } else {
          const result = await addArticle(formData)
          if (type === 'draft' && !closeDialog && result.data) {
            articleForm.id = result.data.id
          }
        }
        
        ElMessage.success(type === 'publish' ? '发布成功' : '保存成功')
        if (closeDialog) {
          dialog.visible = false
        }
        handleQuery()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 分页方法
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  handleQuery()
}

// 标题点击事件
const handleTitleClick = (row: any) => {
  router.push(`/notice/detail/${row.id}`)
}

// 上移文章
const handleMoveUp = async (row: any, index: number) => {
  if (index === 0) return
  const prevRow = articleList.value[index - 1]
  try {
    await updateArticleOrder(Number(row.id), Number(prevRow.orderNum))
    await updateArticleOrder(Number(prevRow.id), Number(row.orderNum))
    ElMessage.success('移动成功')
    handleQuery()
  } catch (error) {
    console.error('移动失败:', error)
    ElMessage.error('移动失败')
  }
}

// 下移文章
const handleMoveDown = async (row: any, index: number) => {
  if (index === articleList.value.length - 1) return
  const nextRow = articleList.value[index + 1]
  try {
    await updateArticleOrder(Number(row.id), Number(nextRow.orderNum))
    await updateArticleOrder(Number(nextRow.id), Number(row.orderNum))
    ElMessage.success('移动成功')
    handleQuery()
  } catch (error) {
    console.error('移动失败:', error)
    ElMessage.error('移动失败')
  }
}

// 添加上传相关方法
const handleCoverSuccess = (response: any) => {
  console.log('上传响应:', response)
  if (response.code === 200) {
    articleForm.coverUrl = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const beforeCoverUpload = (file: File) => {
  console.log('准备上传文件:', file)
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 初始化
handleQuery()
</script>

<style>
/* TinyMCE 样式修复 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}
.tox-dialog-wrap {
  z-index: 99999 !important;
}
</style>

<style lang="scss" scoped>
.article-manage {
  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .search-box {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;

      .el-select {
        width: 120px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.tox-tinymce) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100% !important;
}

.cover-uploader {
  .cover-image {
    width: 300px;
    height: 150px;
    display: block;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 150px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration);
    display: flex;
    align-items: center;
    justify-content: center;
    
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 